<template>
    <!-- 顶部功能区 -->
    <h1>{{ sourceType === "preReserve" ? "预储成员导入" : "军事兴趣类社团成员导入" }}</h1>
    <div id="top" class="top-container">
        <div class="search-container">
            <!-- 姓名、学号、学院 -->
            <label for="qName" class="left-align">姓名：</label>
            <input id="qName" type="text" v-model="qName" placeholder="请输入姓名" class="input-field">

            <label for="qStudentId" class="left-align">学号：</label>
            <input id="qStudentId" type="text" v-model="qStudentId" placeholder="请输入学号" class="input-field">

            <label for="qCollege" class="left-align">学院：</label>
            <input id="qCollege" type="text" v-model="qCollege" placeholder="请输入学院" class="input-field">

            <!-- 性别下拉选择框 -->
            <label for="qGender" class="left-align">性别：</label>
            <select id="qGender" v-model="qGender" class="input-field">
                <option value="">请选择</option>
                <option value="1">男</option>
                <option value="0">女</option>
            </select>

            <!-- 搜索按钮 -->
            <el-button type="primary" :loading='isSearchLoding' @click="conditionPageQuery(currentPage, pageSize)"
                class="search-btn">搜索</el-button>
            <el-button @click="addJoinArmyMembers" type="primary" style="width:100px">
                添加为入伍成员
            </el-button>
        </div>
    </div>

    <!-- 表格展示区 -->
    <el-table :data="tableData" row-key="studentId" max-height="500" style="width: 100%;text-align: center;"
        @selection-change="handleSelectionChange" :header-cell-style="{ background: '#eef1f6', color: '#2c2c3b' }"
        :scroll-x="true">
        <el-table-column type="selection" width="30"></el-table-column>
        <el-table-column label="序号" align="center" fixed width="60">
            <template #default="scope">
                {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
        </el-table-column>
        <el-table-column prop="studentId" label="学号" align="center" min-width="150" />
        <el-table-column prop="name" label="姓名" align="center" width="80" />
        <el-table-column label="性别" align="center" width="60">
            <template #default="scope">
                {{ scope.row.gender === "1" ? '男' : scope.row.gender === "0" ? '女' : '未知' }}
            </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期" sortable align="center" width="120" />
        <el-table-column prop="college" label="学院" align="center" min-width="120" />
        <el-table-column prop="contactNumber" label="电话" align="center" min-width="120" />
        <el-table-column label="操作" align="center" fixed="right" min-width="180">
            <template #default="scope">
                <!-- 添加按钮 -->
                <el-button type="primary" @click="addJoinArmyMember(scope.row.studentId)" class="add-btn">
                    添加
                </el-button>
                <!-- 查看详细信息按钮 -->
                <el-button @click="getDetailInfo(scope.row.studentId)" class="detail-btn">
                    查看详细信息
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 底部分页导航栏 -->
    <div class="page-nav">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" hide-on-single-page="true"
            layout="total, prev, pager, next, sizes" background :page-sizes="[5, 10, 20, 50]" :size="size"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 个人详细信息对话框 -->
    <el-dialog v-model="isMemberInfo" style="top: -100px;" width="65%" center>
        <MemberInfo v-model="isMemberInfo" :studentId="MemberInfoStudentId" :sourceType="props.sourceType" />
    </el-dialog>

    <!-- 点击添加后，提交个人信息对话框 -->
    <el-dialog v-model="isExistForm" style="top: -100px;" width="65%" center>
        <ExistForm v-if="isExistForm" :type="sourceType" :memberInfo="toMemberInfo"
            :currentIndex="currentMemberIndex - 1" :totalMembers="joinArmyInfoList.length" @submit="handleMemberSubmit"
            @cancel="isExistForm = false" />
    </el-dialog>

</template>



<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import MemberInfo from './MemberInfo.vue';
import ExistForm from './ExistForm.vue';
import { ElMessage } from 'element-plus';
import { getMemberInfo, getPagePOrP } from '@/api/join-army/join-army';

const props = defineProps({
    modelValue: {
        type: Boolean,
        required: true,
    },
    sourceType: {
        type: String,
        required: true
    }
});

//个人信息页面展示与否
const isMemberInfo = ref(false);
const isExistForm = ref(false);

//给MemberInfo组件传递的值
const MemberInfoStudentId = ref()
const toMemberInfo = ref();

// 分页相关数据
const size = ref('default');
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

// Loading数据
const isSearchLoding = ref(false);

// 查询参数定义
const qName = ref("");
const qStudentId = ref("");
const qCollege = ref("");
const qGender = ref("");

function initSearch() {
    qName.value = '',
    qStudentId.value = '',
    qCollege.value = '',
    qGender.value = ''
}

// 选中的成员信息
const selectedMembers = ref([]);


// 监听父组件的 v-model 变化
watch(
    () => props.modelValue,
    (newVal) => {
        if (newVal) {
            // 当父组件重新显示子组件时，调用 conditionPageQuery刷新页面
            initSearch();//初始化搜索框
            conditionPageQuery(currentPage.value, pageSize.value);
        }
    }
);

// 入伍成员表单
const joinArmyInfoList = ref([]);

// 获取批量入伍成员信息的逻辑
function addJoinArmyMembers() {
    if (selectedMembers.value.length === 0) {
        ElMessage.warning('请先选择成员！');
        return;
    }
    addJoinArmy(selectedMembers.value);
}
// 获取单个为入伍成员信息的逻辑
function addJoinArmyMember(studentId: string) {
    addJoinArmy([studentId])
}
const addJoinArmy = (studentIds) => {
    const data = {
        studentIds,
        type: props.sourceType//表示是预征班成员还是预储成员
    };
    getMemberInfo(data).then(result => {
        joinArmyInfoList.value = result.data;
        currentMemberIndex.value = 0;
        isExistForm.value = true;
        showNextMember();
    }).catch(error => {
        ElMessage.error("获取数据失败！")
        console.log("获取数据失败", error);
    });
}

const currentMemberIndex = ref(0);
const showNextMember = () => {
    if (currentMemberIndex.value < joinArmyInfoList.value.length) {
        toMemberInfo.value = joinArmyInfoList.value[currentMemberIndex.value];
        currentMemberIndex.value++;
    } else {
        isExistForm.value = false;
        //ElMessage.success('所有成员已处理完毕！');
        conditionPageQuery(currentPage.value, pageSize.value);//提交完后刷新页面
    }
}

// 监听 ExistForm 组件的提交事件
const handleMemberSubmit = () => {
    showNextMember(); // 提交成功后展示下一个成员
}

// 多选框 选择项发生变化时触发
function handleSelectionChange(selection) {
    selectedMembers.value = selection.map(item => item.studentId);
}

// 表格展示数据
let tableData = ref([]);

// 条件分页查询获取所有的成员
function conditionPageQuery(page, pageSize) {
    isSearchLoding.value = true;
    const params = {
        page,
        pageSize,
        name: qName.value,
        studentId: qStudentId.value,
        college: qCollege.value,
        gender: qGender.value,
        status: 1//表示只查预征班现役
    };
    const url = props.sourceType === "preReserve" ? "/admin/preReserve/members" : "/admin/preparatory/members";
    getPagePOrP(url, params).then(result => {
        // 预储和预征班返回电话名，不一致，修改重命名处理
        if (props.sourceType === "preReserve") {
            tableData.value = result.data.records.map(({ telephone, ...rest }) => ({
                ...rest,
                contactNumber: telephone
            }));
        } else {
            tableData.value = result.data.records;
        };
        total.value = result.data.total;
        isSearchLoding.value = false;
    });
}

//查看学生详细信息
// 定义 getDetailInfo 方法
function getDetailInfo(studentId) {
    isMemberInfo.value = true;
    MemberInfoStudentId.value = studentId;
}

// 每页显示条目个数变化
const handleSizeChange = (val) => {
    conditionPageQuery(currentPage.value, val);
};

// 当前页码变化
const handleCurrentChange = (val) => {
    conditionPageQuery(val, pageSize.value);
};

// 组件实例挂载完成之后 调用函数获取相关数据
onMounted(() => {
    conditionPageQuery(currentPage.value, pageSize.value);
});
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}

#top {
    max-width: 100%;
    display: flex;
    align-items: center;
    flex-direction: column;
    padding: 20px;
    background-color: #f4f5f6;
    border-radius: 8px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.input-field {
    padding: 8px;
    border-radius: 8px;
    border: 1px solid #dcdfe6;
    font-size: 14px;
}

.left-align {
    width: 80px;
    text-align: center;
    margin-left: 10px;
}

.search-btn {
    width: 70px;
    margin-left: 20px;
    padding: 8px 16px;
    font-size: 14px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.search-btn:hover {
    background-color: #45a049;
}

.page-nav {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.detail-btn {
    text-decoration: none;
    color: inherit;
    border: none;
    background: none;
    padding: 0;
    font: inherit;
    cursor: pointer;
    outline: none;
    background-color: #2fd8f9;
    color: white;
    padding: 5px 5px;
    text-align: center;
    display: inline-block;
    font-size: 12px;
    border-radius: 5px;
    margin-left: 10px;
    /* 与添加按钮的间距 */
}

.detail-btn:hover {
    background-color: #4eb4d6;
}

.add-btn {
    padding: 1px 10px;
}
</style>